package com.example.backstage.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.backstage.config.security.LoginUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtil {
    private static String key = "wqiehuqwhoenak412sjdna1231k";

    public static String createJwt(LoginUserDetails userDetails, Integer id, String username) {
        Algorithm algorithm = Algorithm.HMAC256(key);
        return JWT.create()
                .withClaim("id", id)
                .withClaim("name", username)
                .withClaim("authority", userDetails.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList())
                .withExpiresAt(expireTime())
                .withIssuedAt(new Date())
                .sign(algorithm);
    }

    public static Date expireTime() {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, 7);
        return instance.getTime();
    }

    //根据Jwt验证并解析用户信息
    public static UserDetails resolveJwt(String token) {
        if (token.isBlank()) {
            return null;
        }

        Algorithm algorithm = Algorithm.HMAC256(key);
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        try {
            DecodedJWT verify = jwtVerifier.verify(token);  //对JWT令牌进行验证，看看是否被修改
            Map<String, Claim> claims = verify.getClaims();  //获取令牌中内容
            if (new Date().after(claims.get("exp").asDate())) //如果是过期令牌则返回null
                return null;
            else
            //重新组装为UserDetails对象，包括用户名、授权信息等

            {
                com.example.backstage.entity.User user = new com.example.backstage.entity.User();
                user.setId(claims.get("id").asInt());
                user.setName(claims.get("name").asString());
                return new LoginUserDetails(user);
            }

        } catch (JWTVerificationException e) {
            return null;
        }
    }


}
